package org.lql.algo.codecrush.hot100.doublePointer;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author: liangqinglong
 * @date: 2025-09-08 11:28
 * @description: 42. 接雨水 <a href="https://leetcode.cn/problems/trapping-rain-water/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 **/
public class Trap {

	public int trap(int[] height) {
		int n = height.length;
		Deque<Integer> queue = new ArrayDeque<>();
		int ans = 0;
		for (int i = 0; i < n; i++) {
			while (!queue.isEmpty() && height[i] > height[queue.peek()]) {
				int bottom = queue.pop(); // 当前低洼处
				if (queue.isEmpty()) {
					break;
				}
				int left = queue.peek();
				int width = i - left - 1;
				int currentHeight = Math.min(height[left], height[i]) - height[bottom];
				ans += width * currentHeight;
			}
			queue.push(i);
		}
		return ans;
	}

	public static void main(String[] args) {
		int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
		Trap trap = new Trap();
		System.out.println(trap.trap(height));
	}
}
